﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Eneta.Portal.Common;
using Eneta.Portal.Common.Dto;
using Eneta.Portal.Common.Repository;
using Microsoft.SharePoint;

namespace Eneta.Portal.Companies.Controls
{
    public class IOResultsControl : UserControl 
    {
        protected HtmlGenericControl filterArea;
        protected Repeater resultsRepeater;

        protected HtmlGenericControl slideBoxContainer;
        protected HtmlGenericControl navContainer;
        protected HtmlGenericControl userNameLabel;

        protected HtmlGenericControl sortByModifiedContainer;
        protected HtmlAnchor sortByModifiedLink;
        protected HtmlGenericControl sortByNameContainer;
        protected HtmlAnchor sortByNameLink;

        protected HtmlGenericControl prevResultsContainer;
        protected HtmlGenericControl nextResultsContainer;
        protected HtmlGenericControl prevResultsBottomContainer;
        protected HtmlGenericControl nextResultsBottomContainer;

        protected HtmlAnchor prevResultsLink;
        protected HtmlAnchor nextResultsLink;
        protected HtmlAnchor footerNextLink;
        protected HtmlAnchor footerPrevLink;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            resultsRepeater.ItemDataBound += ResultsRepeaterItemDataBound;
        }

        private string _sort;
        private string _asc;

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            // Detect sort order
            _sort = Request.QueryString["sort"] ?? "modified";
            _sort = _sort.ToLower();
            
            _asc = Request.QueryString["asc"] ?? "0";

            if (_asc != "1" && _asc != "0")
                _asc = "1";

            switch(_sort)
            {
                case "name":
                    break;
                default:
                    _sort = "modified";
                    break;
            }
           

            var county = Request.QueryString["county"];
            var partnership = Request.QueryString["partnership"];
            var emp = Request.QueryString["emp"];

            var repository = new CompanyRepository(SPContext.Current.Web);
            var results = repository.GetCompanyResults();
            IList<CompanyDto> pageResults = null;
            //var results = CompanyQueryManager.Resulst();

            if (results != null)
            {
                if (_asc == "1")
                    if (_sort == "name")
                        results = results.OrderBy(p => p.Title).ToList();
                    else
                        results = results.OrderBy(p => p.Modified).ToList();
                else 
                    if (_sort == "name")
                        results = results.OrderByDescending(p => p.Title).ToList();
                    else
                        results = results.OrderByDescending(p => p.Modified).ToList();

                var pageSize = 15;
                var pages = (int)Math.Ceiling(results.Count/(double)pageSize);
                var page = GetPageNumber(pages);
                pageResults = results.Skip((page-1)*pageSize).Take(pageSize).ToList();

                var queryParts = (from s in Request.QueryString.AllKeys
                                  where s.ToLower() != "pg"
                                  select s + "=" + Request.QueryString[s])
                                .ToArray();
                var queryString = string.Join("&", queryParts);
                if(!string.IsNullOrEmpty(queryString))
                    if (queryString.StartsWith("&"))
                        queryString = queryString.Substring(1);


                prevResultsLink.HRef = "/firmad/Lehed/Default.aspx?" + queryString;
                if (!string.IsNullOrEmpty(queryString))
                    prevResultsLink.HRef += "&";
                prevResultsLink.HRef+= "pg=" + Math.Max(1, page - 1);

                nextResultsLink.HRef = "/firmad/Lehed/Default.aspx?" + queryString;
                if (!string.IsNullOrEmpty(queryString))
                    nextResultsLink.HRef += "&";
                nextResultsLink.HRef+= "pg=" + Math.Min(page + 1, pages);

                if (page <= 1)
                    prevResultsContainer.Visible = false;
                if (page >= pages)
                    nextResultsContainer.Visible = false;

                footerPrevLink.HRef = prevResultsLink.HRef;
                footerNextLink.HRef = nextResultsLink.HRef;
                prevResultsBottomContainer.Visible = prevResultsContainer.Visible;
                nextResultsBottomContainer.Visible = nextResultsContainer.Visible;
            }

            var user = SPContext.Current.Web.CurrentUser;
            slideBoxContainer.Visible = false; // (user != null);
            navContainer.Visible = (user != null);

            if (user != null)
                userNameLabel.InnerText = user.Name;

            var filterList = new List<string>();
            if (!string.IsNullOrEmpty(county))
                filterList.Add(county);
            if (!string.IsNullOrEmpty(partnership))
                filterList.Add(partnership);
            if (!string.IsNullOrEmpty(emp))
                filterList.Add(emp + " töötajat");

            var filterOutput = string.Empty;

            if (filterList.Count > 0)
            {
                var filterParts = filterList.ToArray();
                filterOutput = string.Join(" <span>+</span> ", filterParts);
                filterOutput += " <span>=</span> ";
            }
            if (results == null)
                filterOutput += "<strong>0</strong/>";
            else
                filterOutput += "<strong>" + results.Count + "</strong>";
            filterOutput += " firmat";
            filterArea.InnerHtml = filterOutput;

            try
            {
                resultsRepeater.DataSource = pageResults;
                resultsRepeater.DataBind();
            }
            catch(Exception ex)
            {
                Logger.LogWarning("OnLoad(): Exception when binding results", GetType().ToString());
                Logger.LogException(ex);
            }
        }

        protected int GetPageNumber(int maxPages)
        {
            var pgString = Request.QueryString["pg"];
            if (string.IsNullOrEmpty(pgString))
                pgString = "1";

            int page;
            if (!int.TryParse(pgString, out page))
                page = 1;

            if (page < 1)
                page = 1;

            if(maxPages > 0)
            {
                page = Math.Min(page, maxPages);
            }

            return page;
        }

        protected void SetPagerLinks()
        {
            
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            var queryParts = new List<string>();
            if(Request.QueryString != null)
                foreach(string key in Request.QueryString.Keys)
                    if(key.ToLower() != "sort" && key.ToLower() != "asc")
                        queryParts.Add(key + "=" + Request.QueryString[key]);
            var query = string.Join("&", queryParts.ToArray());

            var asc = (_asc == "0" ? "1" : "0");
            string url;
            var urlPref = "/firmad/Lehed/default.aspx?" + query;
            if (!urlPref.EndsWith("?"))
                urlPref += "&";

            // Modified 
            if(_sort == "modified")
            {
                url = urlPref+ "sort=modified&asc=" + asc;
                sortByModifiedContainer.Attributes["class"] = "active";
                sortByModifiedLink.HRef = url;

                url = urlPref + "sort=name&asc=1";
                sortByNameContainer.Attributes["class"] = string.Empty;
                sortByNameLink.HRef = url;
            }
            else
            {
                url = urlPref + "sort=modified&asc=1";
                sortByModifiedContainer.Attributes["class"] = "";
                sortByModifiedLink.HRef = url;
                
                url = urlPref + "sort=name&asc=" + asc;
                sortByNameContainer.Attributes["class"] = "active";
                sortByNameLink.HRef = url;
            }

            SetPagerLinks();
        }

        protected void ResultsRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            var company = (CompanyDto)e.Item.DataItem;
            var logoContainer = (HtmlGenericControl)e.Item.FindControl("logoContainer");
            var companyTitle = (HyperLink)e.Item.FindControl("companyTitle");
            var companyDescription = (Label)e.Item.FindControl("companyDescription");
            var peopleLabel = (Label)e.Item.FindControl("peopleLabel");
            var locationLabel = (Label)e.Item.FindControl("locationLabel");
            var modifiedDate = (Label)e.Item.FindControl("modifiedDate");
            var companyLink = (HyperLink)e.Item.FindControl("companyLink");
            var companyLogo = (HtmlImage)e.Item.FindControl("companyLogo");
            var logoLink = (HtmlAnchor)e.Item.FindControl("logoLink");
            var partnerLogo = (HtmlImage)e.Item.FindControl("partnerLogo");

            //companyTitle.NavigateUrl = "/firmad/Lehed/" + row["LinkFilename"] + "?" + Request.ServerVariables["QUERY_STRING"];
            companyTitle.NavigateUrl = "/firmad/Lehed/" + company.FileName + "?" + Request.ServerVariables["QUERY_STRING"];
            if (companyTitle.NavigateUrl.EndsWith("?"))
                companyTitle.NavigateUrl = companyTitle.NavigateUrl.Substring(0, companyTitle.NavigateUrl.Length - 1);
            companyTitle.Text = company.Title;

            //var fileName = row["FileLeafRef"].ToString().Replace(".aspx", "_small.png");
            var fileName = company.FileName.Replace(".aspx", "_small.png");
            var logoUrl = "/SiteCollectionImages/firmad/" + fileName;
            var logoFile = SPContext.Current.Site.RootWeb.GetFile(logoUrl);

            if (logoFile.Exists)
            {
                logoContainer.Visible = true;
                companyLogo.Src = logoUrl;
                logoLink.HRef = companyTitle.NavigateUrl;
            }
            else
            {
                companyLogo.Src = string.Empty;
                logoContainer.Visible = true;
                logoContainer.InnerHtml = "&nbsp;";
                //logoContainer.Visible = false;                
            }
            
            //companyDescription.Text = row["Comments"].ToString();
            companyDescription.Text = company.ShortDescription;
            if (company.Offices.Count > 0)
            {
                var offList = new List<string>();
                foreach(var off in company.Offices)
                {
                    offList.Add(off.Title);
                }
                locationLabel.Text = string.Join(", ", offList.ToArray());
            }
            peopleLabel.Text = company.Employees;
            modifiedDate.Text = company.Modified.ToShortDateString();
            companyLink.NavigateUrl = companyTitle.NavigateUrl;
            
            partnerLogo.Visible = false;
            if (company.PartnershipLevel!=null)
            {
                if (company.PartnershipLevel != string.Empty)
                {
                    var certPath = "/Style Library/eneta/images/" + company.PartnershipLevel.ToLower().Replace(" ", "-") + "_small.gif";
                    var certFile = SPContext.Current.Site.RootWeb.GetFile(certPath);
                    if (certFile.Exists)
                    {
                        partnerLogo.Src = certPath;
                        partnerLogo.Visible = true;
                        if (certPath.ToLower().Contains("gold") || certPath.ToLower().Contains("kuld"))
                            partnerLogo.Alt = "Gold Certified Partner";
                        else
                            partnerLogo.Alt = "Certified Partner";
                    }
                }
            }
        }

    }
}
